package com.kinglone.back.user.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.kinglone.back.user.model.User;
import com.kinglone.back.user.service.UserService;
import com.kinglone.common.utils.CryptoUtil;
import com.kinglone.common.utils.ResponseUtil;

@Controller
@RequestMapping("/back/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	/**
	 * 登陆
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping("/login.do")
	public String login(HttpServletRequest request,User user){
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),CryptoUtil.md5(user.getPassword(), "kinglone"));
		System.out.println("----token:"+token);
		try {
			subject.login(token);//登陆验证
			return "redirect:/back/main.jsp";
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("user", user);
			request.setAttribute("errorInfo", "用户名或密码错误！");
			return "login";
		}
	}
	/**
	 * 修改密码
	 * @param newPassword
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/modifyPassword")
	public String modifyPassword(String newPassword,@RequestParam(value="sysid")String sysid,HttpServletResponse response) throws Exception{
		User user = new User();
		user.setSysid(sysid);
		user.setPassword(CryptoUtil.md5(newPassword, "kinglone"));
		int resultTotal = userService.update(user);
		JSONObject result=new JSONObject();
		if(resultTotal>0){
			result.put("success", true);
		}else{
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
	}
	
	
	/**
	 * 注销
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout()throws Exception{
		SecurityUtils.getSubject().logout();
		return "redirect:/login.jsp";
	}
}
